import { eachNode } from './utils/each_node';
import {
  changeNode,
  harmlessPrograms,
  effectivePrograms,
} from './utils/change_node';
import { eachStyleProperty } from './utils/each_property';
import { changeProperty } from './utils/change_property';
// import { pageStatus } from './utils/page_status';
import { isAllFinished, isAllFailed } from './utils/style_sheet_retry';

interface MyContext {
  // initialStatus: string; // 每次切换开始时采集的页面状态
  changeNow: boolean; // 立即切换颜色
  userAction: boolean; // 用户点击了切换按钮
  downgraded: boolean; // 使用模式二切换颜色
}

const myContext: MyContext = {
  // initialStatus: pageStatus(),
  changeNow: false,
  userAction: false,
  downgraded: false,
};

let timer: NodeJS.Timeout | null = null;

function clearTimer() {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
}

function checkEffect() {
  clearTimer();

  if (!isAllFinished()) {
    timer = setTimeout(checkEffect, 1000);
    return;
  }

  if (isAllFailed()) {
    console.log('暗影-->模式一降级到模式二-->反转色彩(^-^)');
    myContext.downgraded = true;

    eachNode(document.body, changeNode.bind(null, effectivePrograms));
    eachNode(document.body, changeNode.bind(null, harmlessPrograms));
  }
  // const curPageStatus = pageStatus();
  // console.log(
  //   'debug checkEffect (result, init, current)',
  //   curPageStatus === myContext.initialStatus,
  //   myContext.initialStatus,
  //   curPageStatus
  // );
  // if (curPageStatus === myContext.initialStatus) {
  //   console.log('debug checkEffect', 'going to effect some background');
  //   eachNode(document.body, changeNode.bind(null, effectivePrograms));
  //   eachNode(document.body, changeNode.bind(null, harmlessPrograms));
  // }
}

function eachStylePropertyProxy(force: boolean) {
  clearTimer();
  eachStyleProperty(force, changeProperty);
  timer = setTimeout(checkEffect, 1000);
}

// 监听整个文档树的变化
const observer = new MutationObserver(() => {
  if (myContext.changeNow && !myContext.downgraded) {
    console.log('暗影-->节点发生了变化-->反转色彩(^-^)');

    eachStylePropertyProxy(false);
  }
});
observer.observe(document.documentElement, {
  childList: true,
  subtree: true,
});
window.addEventListener(
  'beforeunload',
  () => {
    observer.disconnect();
  },
  false
);

// 请求后台数据，并相应后台的请求
const portToBG = browser.runtime.connect();
portToBG.onMessage.addListener((msg: MyContext) => {
  myContext.changeNow = msg.changeNow;
  myContext.userAction = msg.userAction;

  // 反转颜色
  if (myContext.changeNow) {
    // myContext.initialStatus = pageStatus();
    console.log('暗影-->用户操作-->立刻反转色彩(^-^)');

    eachStylePropertyProxy(myContext.userAction);
  }

  // 后处理：设计为可以在任何情况下执行
  // - 将前景色与背景色相同的前景色反转
  eachNode(document.body, changeNode.bind(null, harmlessPrograms));
});
window.addEventListener(
  'load',
  () => {
    portToBG.postMessage({ isActived: true });
  },
  false
);
